﻿using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;

namespace LibUpdate
{
    class Base
    {
        /// <summary>
        /// 下载出错重试次数
        /// </summary>
        private int _ErrRECount = 3;


        /// <summary>
        /// 服务器版本信息文件名
        /// </summary>
        public const string ServerVersion = "serverversion.xml";
        /// <summary>
        /// 客户端版本信息文件名
        /// </summary>
        public const string ClientVersion = "clientversion.xml";
        /// <summary>
        /// 升级文件存放目录
        /// </summary>
        public const string UpdatePath = @"\update";
 




        /// <summary>
        /// 下载出错重试次数
        /// </summary>
        public int ErrRECount {
            get { return _ErrRECount; }
            set { _ErrRECount = value; }
        }
        /// <summary>
        /// 通过md5校验文件知否完整
        /// </summary>
        /// <param name="file">文件路径</param>
        /// <param name="md5_str">标准md5值</param>
        /// <returns>返回是否完整</returns>
        public static bool MD5Check(string file, string md5_str)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            bool iswz = false;
            //判断文件是否存在
            if (System.IO.File.Exists(file))
            {
                //获取文件流，并获得md5值
                using (System.IO.Stream st = new System.IO.FileStream(file, System.IO.FileMode.Open))
                {
                    byte[] result = md5.ComputeHash(st);
                    st.Close();
                    
                    //判断md5是否一致
                    StringBuilder sBuilder = new StringBuilder();

                    //判断md5是否一致
                    for (int i = 0; i < result.Length; i++)
                    {
                        sBuilder.Append(result[i].ToString("x2"));
                    }

                    if (sBuilder.ToString() == md5_str)
                    {
                        iswz = true;
                    }
                }
            }
            return iswz;
        }

        /// <summary>
        /// 将版本字符串x.x.x.x转换为数字版本,版本号必须以1开到
        /// </summary>
        /// <param name="verstr">版本字符串</param>
        public static long StrVertoInt(string verstr) {
            long ver = 0;
            if (verstr.Trim() != string.Empty) {
                int verstr_Length = verstr.Replace('.', new char()).Length;
                string[] ver_array = verstr.Split('.');

                //子版本占用位数
                int subversj = 0;
                //版本计算
                for (int i = 0; i < ver_array.Length; i++) {
                    int subver = int.Parse(ver_array[i]);

                    subversj += ver_array[i].Length;

                    ver += (long)(subver * Math.Pow(10, verstr_Length - subversj));
                }
            }
            return ver;
        }

    }
}
